<script>
export default {
  name: "Password",
  data() {
    const validatePassword = (rule, confirmPass, callback) => {
      if (confirmPass ===null) {
        callback(new Error('请确认密码'))
      } else if (confirmPass !== this.user.password) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback();
      }
    };
    const validateEmail = (rule, email, callback) => {
      const reg = /^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$/;
      if (email == null) {
        this.pass = false;
        callback(new Error('请输入邮箱地址'))
      } else if (!reg.test(email)) {
        this.pass = false;
        callback(new Error('请输入正确的邮箱地址'))
      }

        this.request.get("/user/verifyUserEmail",{params:{
          userName:this.userName,
            email:this.user.email
          }}).then(res=>{
          if(res.code!=200){
            this.pass = false;
            callback(new Error(res.msg))
          }else{
            callback();
           this.pass=true;
          }
        })

    };

    const validateCode = (rule, code, callback) => {
     console.log("---------------------")
      if (code == '') {
        callback(new Error('请输入动态码'))
      }else if(code.length!=6){
        callback(new Error('动态码为6位'))
      }else{
        this.request.get("/user/verifyEmailCode", {
          params: {
            email: this.user.email,
            dynamicCode:this.user.verificationCode
          }
        }).then(res => {
          if(res.code!=200){
            callback(new Error('动态码错误或过期，请重新获取'))
          }else{
            callback();
          }
        })
      }
    };

    const validateOriginalPassword=(rule, originalPassword, callback) => {
      if(originalPassword==null){
        callback(new Error("请输入你原来的密码"));
      }
        this.request.get("/user/verifyOriginalPassword",{params:{
          userName:this.userName,originalPassword:this.user.originalPassword
          }}).then(res=>{
            if(res.code!=200){
              callback(new Error(res.msg));
            }else{
              callback();
            }
        })

    };
    return {
      activeStep: 0,
      userName: localStorage.getItem("user")? JSON.parse(localStorage.getItem("user")).userName :null,
      user: {
        email: null,
        verificationCode: null,
        originalPassword: null,
        password: null,
        confirmPass: null,
      },
      disabled: false,
      disabled1:true,
      second: null,
      timer: null,
      pass:false,
      rules1: {
        email: [
          {validator: validateEmail, trigger: 'blur'},
        ],
        verificationCode: [
          {validator: validateCode, trigger: 'blur'},
        ]},
      rules2:{
        originalPassword: [
          {validator: validateOriginalPassword, trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 6, max: 25, message: '密码至少6位', trigger: 'blur'}
        ],
        confirmPass: [
          {validator: validatePassword, trigger: 'blur'}
        ]}
    }
  },
  methods:{
    countTime() {
      const TIME_COUNT = 180;
      if (!this.timer) {
        this.second = TIME_COUNT;
        this.disabled = true;
        this.timer = setInterval(() => {
          if (this.second > 0 && this.second <= TIME_COUNT) {
            this.second--;
          } else {
            this.disabled = false;
            clearInterval(this.timer);
            this.timer = null;
          }
        }, 1000);
      }
    },
    getCode() {
      if (this.pass) {
        this.countTime();
        this.request.get("/user/sendEmailCode", {
          params: {
            email: this.user.email
          }
        }).then(res => {
          if(res.code===200){
            this.$message({
              message:'动态码已发送到您的邮箱，请及时查看',
              type:'success',
              center:true
            });
          }else{
            this.$message({
              message:'动态码发送失败，请重新获取',
              type:'success',
              center:true
            });
          }
        })
      }
    },
    next(){
      this.$refs['emailRef'].validate((valid) => {
        if(valid){
          this.user.email=null;
          this.user.verificationCode=null;
          this.activeStep++;
        }
    })
  },
    next1(){
     this.activeStep++;
    },
    modifyPassword(){
      this.$refs['passwordRef'].validate((valid)=>{
        console.log(valid);
         if(valid){
           this.request.get("/user/updatePassword",{params:{
             userName:this.userName,password:this.user.password
             }}).then(res=>{
               if(res.code===200){
                 setTimeout(()=>{ this.$store.commit("logout");},10000)
                 this.$message({
                   message: '密码重置成功，请点击下一步完成修改',
                   type: 'success',
                   center: true
                 });
               this.disabled1=false;
               }else{
                 this.$message({
                   message: '密码重置失败，请重新尝试',
                   type: 'error',
                   center: true
                 });
               }
           })
         }
      })
    },
    logout(){
      this.$store.commit("logout");
    }
  },
  computed:{
    content() {
      return this.disabled ? `${this.second}s后重新获取` : '获取动态码';
    }
  }

}
</script>

<template>
  <el-card style="width:500px;height:600px">
    <div>
      <el-steps :active="activeStep" finish-status="success" align-center style="margin-top: 50px">
        <el-step title="身份验证"></el-step>
        <el-step title="重置密码"></el-step>
        <el-step title="修改完成"></el-step>
      </el-steps>

      <div v-if="activeStep === 0" style="margin-top: 50px;padding-left: 50px">
        <el-form style="width: 90%" :rules="rules1" :model="user" ref="emailRef" key="email">
          <el-form-item prop="email">
            <el-input prefix-icon="el-icon-message" size="medium" placeholder="请输入邮箱" style="width: 250px"
                v-model="user.email"  clearable></el-input>
          </el-form-item>
          <el-form-item prop="verificationCode">
            <el-input prefix-icon="el-icon-chat-dot-square" size="medium" placeholder="请输入动态码"
                v-model="user.verificationCode"      style="width: 150px" clearable></el-input>
            <el-button type="info" style="height:35px;margin-left: 10px" :disabled="disabled" @click="getCode">
              {{ content }}
            </el-button>
          </el-form-item>
            <el-button type="primary" plain style="height:35px;" @click="next">下一步<i class="el-icon-d-arrow-right"></i></el-button>
        </el-form>
        <!-- 身份验证步骤的内容 -->

      </div>

      <div v-if="activeStep === 1" style="margin-top: 50px;padding-left: 50px">
        <!-- 重置密码步骤的内容 -->
        <el-form style="width: 90%" :rules="rules2" :model="user" ref="passwordRef" key="password">
          <el-form-item prop="originalPassword">
            <el-input prefix-icon="el-icon-lock" size="medium" placeholder="请输入原密码" style="width: 250px"
                      v-model="user.originalPassword" show-password clearable></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input prefix-icon="el-icon-lock" size="medium" placeholder="请输入新密码" style="width: 250px"
                      v-model="user.password" show-password clearable></el-input>
          </el-form-item>
          <el-form-item prop="confirmPass">
            <el-input prefix-icon="el-icon-lock" size="medium" placeholder="请确认新密码" style="width: 250px"
                      v-model="user.confirmPass" show-password clearable></el-input>
            <el-button type="primary" style="height:37px;margin-left:10px" @click="modifyPassword">重置密码</el-button>
          </el-form-item>
          <el-button-group>
            <el-button type="primary" icon="el-icon-d-arrow-left" style="height:35px;" @click="activeStep--">上一步</el-button>
            <el-button type="primary"  :disabled="disabled1" @click="next1" style="height:35px;">下一步<i class="el-icon-d-arrow-right el-icon--right" ></i></el-button>
          </el-button-group>
        </el-form>
      </div>

      <div v-if="activeStep === 2">
        <el-result icon="success" title="修改成功" subTitle="请退出重新登录，否则十秒后将自动退出">
          <template slot="extra">
            <el-button type="warning" size="medium" @click="logout">退出</el-button>
          </template>
        </el-result>
        <!-- 重置完成步骤的内容 -->
      </div>
    </div>
  </el-card>
</template>

<style scoped>

</style>
